<template>
    <el-upload
        :action="uploadHttp"
        list-type="picture-card"
        :auto-upload="true"
        :limit="limitSize"
        :file-list="transFileIdsToUrls(uploadImage)"
        :headers="{ token: getToken() }"
        :on-success="(...arg) => uploadSuccess(...arg)"
        :disabled="localDisabled"
        :on-exceed="overLimit"
    >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{ file }">
            <template v-if="file.response != ''">
                <!-- Url 如何统一配置 -->
                <img
                    class="el-upload-list__item-thumbnail"
                    :src="'/api/attachment/download?fileId=' + file.response"
                    alt=""
                />
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-delete" @click="remove(file)">
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </template>
        </div>
    </el-upload>
</template>

<script>
export default {
    name: 'Upload',
    props: {
        uploadImage: {
            type: String,
            default: ''
        },
        disabledUpload: {
            type: Boolean,
            default: false
        },
        limitSize: {
            type: Number,
            default: 5
        }
    },
    data() {
        return {
            uploadHttp: '/api/attachment/uploadFiles',
            fileUpload: [],
            localUploadImage: '',
            localDisabled: false
        };
    },
    watch: {
        uploadImage(n) {
            if (n) {
                console.log('localUploadImage', n);
                this.localUploadImage = n;
            }
        },
        disabledUpload(n) {
            if (n) {
                this.localDisabled = n;
            }
        }
    },
    methods: {
        // 上传成功
        uploadSuccess(response, file, fileList, item, index) {
            console.log(response, file, item, index);
            // 回显本地变量
            let fileArray = this.formatFileListToArray(fileList);
            this.localUploadImage = this.arrayFormatStr(fileArray);
            //双向同步到父组件
            this.$emit('update:uploadImage', this.localUploadImage);
        },
        getToken() {
            let result = sessionStorage.getItem('token');
            return result;
        },
        remove(file) {
            console.log('删除>>>>>>', file.response);

            let uploadImageArray = this.uploadImage.split(',');
            console.log('删除前>>>>', uploadImageArray);
            const index = uploadImageArray.findIndex(fileId => file.response === fileId);
            uploadImageArray.splice(index, 1);
            console.log('删除后>>>>', uploadImageArray);
            //双向同步到父组件
            this.$emit('update:uploadImage', this.arrayFormatStr(uploadImageArray));
        },
        transFileIdsToUrls(uploadImage) {
            if (!uploadImage) {
                return [];
            }
            let fileIdArray = uploadImage.split(',');
            let array = fileIdArray
                .filter(item => {
                    if (item) {
                        return true;
                    }
                })
                .map(fileId => {
                    return { response: fileId };
                });
            return array;
        },
        formatFileListToArray(fileList) {
            let fileArray = [];
            fileList.forEach(file => {
                fileArray.push(file.response);
            });

            return fileArray;
        },
        /**
         * 将数组转成字符串
         * @param array
         */
        arrayFormatStr(array) {
            let str = '';
            if (array && array.length > 0) {
                for (let i = 0; i < array.length; i++) {
                    if (array[i] && array[i] !== undefined) {
                        str += array[i];
                        //最后一个不加 ,
                        if (i !== array.length - 1) {
                            str += ',';
                        }
                    }
                }
            }
            return str;
        },
        /**
         * 文件数量超出以后的钩子
         * files, fileList
         */
        overLimit() {
            this.$message({
                type: 'warning',
                message: '超过最大上传数量'
            });
        }
    }
};
</script>

<style scoped></style>
